package com.dyz.leetcode._07_hashSearch;

import java.util.HashMap;
import java.util.Map;

public class _560_subarraySum {
    //前缀和+哈希查找
    public int subarraySum(int[] nums, int k) {
        int[] prefixSum = new int[nums.length+1];
        prefixSum[0] = 0;
        for(int i=1; i<prefixSum.length;i++){
            prefixSum[i] = nums[i-1]+prefixSum[i-1];
        }
        Map<Integer, Integer> map = new HashMap<>();
        int res = 0;
        for (int i = 0; i < prefixSum.length; i++) {
            int diff = prefixSum[i] - k;
            // 哈希查找
            if (map.containsKey(diff)) {
                res += map.get(diff);
            }
            map.put(prefixSum[i], map.getOrDefault(prefixSum[i], 0) + 1);
        }

        return res;

    }
}
